package com.pingan.glue.gluegame.service.impl;

import com.pingan.glue.gluegame.auth.TokenGenerator;
import com.pingan.glue.gluegame.dao.FriendUserTokenDao;
import com.pingan.glue.gluegame.entity.FriendUserTokenEntity;
import com.pingan.glue.gluegame.service.FriendUserTokenService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class FriendUserTokenServiceImpl implements FriendUserTokenService {
    //12小时后过期
    private final static int EXPIRE = 3600 * 12;

    @Resource
    private FriendUserTokenDao friendUserTokenDao;

    @Override
    public FriendUserTokenEntity queryByToken(String token) {
        return friendUserTokenDao.queryByToken(token);
    }

    @Override
    public String createToken(Long userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //判断是否生成过token
        FriendUserTokenEntity tokenEntity = friendUserTokenDao.selectById(userId);
        if(tokenEntity == null){
            tokenEntity = new FriendUserTokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //保存token
            friendUserTokenDao.insert(tokenEntity);
        }else{
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //更新token
            friendUserTokenDao.updateById(tokenEntity);
        }

        return token;
    }
}
